//
//  NewsOtherViewController.m
//  B-72K
//
//  Created by 张春洋 on 16/3/16.
//  Copyright © 2016年 sos. All rights reserved.
//

#import "NewsOtherViewController.h"
#import "NewsTableViewCell.h"
#import "QPNetWorkingTool.h"
#import <Masonry.h>
#import "NewsDetialViewController.h"
#import <MJRefresh.h>
#import "AllPrefixHeader.pch"
@interface NewsOtherViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)UITableView *newsTableView; // 新闻的tableVIew
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)UILabel *NaviLable;
@property (nonatomic, retain)UIButton *button;
@property (nonatomic, retain)NewsModel *newsModel;




@end

@implementation NewsOtherViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    //解档获取数据
    NSString *path =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //2.拼接地址 (按照什么路径 保存为什么文件) (数组和字典写plist)
    NSString *strpath = [path stringByAppendingPathComponent:@"c.plist"];
    
    NSString *str = [NSKeyedUnarchiver unarchiveObjectWithFile:strpath];
    UIColor *bg = [UIColor colorWithPatternImage:[UIImage imageNamed:str]];
    //     判断当前是什么模式
    [self.view setBackgroundColor:bg];
    _newsTableView.backgroundColor = [UIColor clearColor];
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:str]forBarMetrics:UIBarMetricsDefault];
    
    //    [self.navigationItem.titleView setBackgroundColor:bg];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBarHidden = NO;
    NSString *path =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    //2.拼接地址 (按照什么路径 保存为什么文件) (数组和字典写plist)
    NSString *strpath = [path stringByAppendingPathComponent:@"b.plist"];
    
//    [NSKeyedArchiver archiveRootObject:newsOther.titleStr toFile:strpath];
      self.titleStr = [NSKeyedUnarchiver unarchiveObjectWithFile:strpath];
    self.navigationItem.title = self.titleStr;

    [self dataHandler];
    [self CreatData];
    [self CreatNavi];
    [self refresh];
    [self loading];
}

#pragma mark - 加载
- (void)loading
{
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //延迟两秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString *path =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
            NSString *strpath = [path stringByAppendingPathComponent:@"a.plist"];
            NSString *new  =[NSKeyedUnarchiver unarchiveObjectWithFile:strpath];
            // 非活动
            [QPNetWorkingTool getNetWorkingTool:[NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news?pageSize=20&lastId=%@&columnId=%@&pagingAction=down", _newsModel.feedId, new] dic:nil success:^(id result) {
                NSMutableArray *arr = result[@"data"][@"data"];
                NSMutableArray *tempArr = [NewsModel modelHanderWithArray:arr];
                // 新数据添加到dataArr里
                for (NewsModel *m in tempArr) {
                    [self.dataArr addObject:m];
                }
                [_newsTableView reloadData];
            } fail:^(NSError *error) {
            }];
             [_newsTableView.mj_footer endRefreshing];
        });
    }];
    _newsTableView.mj_footer = footer;
}


#pragma mark - 下拉刷新
- (void)refresh
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //延迟2秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
                       dispatch_get_main_queue(),^{
            // 刷新
            [self dataHandler];
            //新版本是 MJ_header
            [self.newsTableView.mj_header endRefreshing];
        });
    }];
    self.newsTableView.mj_header = header;
    header.stateLabel.font = [UIFont systemFontOfSize:12];
}


- (void)push
{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)CreatNavi
{
    self.NaviLable = [UILabel new];
    self.NaviLable.text =@"其他";
    self.NaviLable.textAlignment = NSTextAlignmentCenter ;
    _NaviLable.backgroundColor = [UIColor colorWithRed:246 /255.0 green:246 /255.0 blue:246 /255.0 alpha:1];
    [self.view addSubview:_NaviLable];
    [self.NaviLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.top.equalTo(self.view.mas_top).offset(0);
        make.height.mas_equalTo(64);
    }];
    self .button = [UIButton new];
    [self.view addSubview:_button];
    _button.backgroundColor = [UIColor colorWithRed:246 /255.0 green:246 /255.0 blue:246 /255.0 alpha:1];
    [_button setTitle:@"回主页" forState:UIControlStateNormal];
    [_button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.width.mas_equalTo(55);
        make.height.mas_equalTo(64);
        make.top.equalTo(self.view.mas_top).offset(0);
    }];
}

- (void)dataHandler
{
    NSString *path =   NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *strpath = [path stringByAppendingPathComponent:@"a.plist"];
    NSString *new  =[NSKeyedUnarchiver unarchiveObjectWithFile:strpath];
    
    NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news?pageSize=20&columnId=%@&pagingAction=up", new];
    NSLog(@"%@",str);
    [QPNetWorkingTool getNetWorkingTool:str dic:nil success:^(id result) {
        self.dataArr = [NewsModel modelHanderWithArray:result[@"data"][@"data"]];
        [self.newsTableView reloadData];
    } fail:^(NSError *error) {
    }];
}

- (void)CreatData
{
        self.newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
        _newsTableView.delegate = self;
        _newsTableView.dataSource = self;
    [_newsTableView NightWithType:UIViewColorTypeNormal];
        [self.view addSubview:_newsTableView];
        [_newsTableView registerClass:[NewsTableViewCell class] forCellReuseIdentifier:@"newsCell"];
        
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsDetialViewController *nwsdetial = [[NewsDetialViewController alloc] init];
    
        NewsModel *m = _dataArr[indexPath.row];
       nwsdetial.str = m.feedId;
   
    [self.navigationController pushViewController:nwsdetial animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    _newsModel = _dataArr.lastObject;
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell" forIndexPath:indexPath];
    [cell NightWithType:UIViewColorTypeNormal];
    cell.news = _dataArr[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
